package com.zwx.linkList.leetcode_5;

/**
 * 合并两个有序链表
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 * @author 文希
 * @create 2019-07-03 23:01
 */
public class MergeTwoLists {

    /**
     * 思路：
     * 递归处理：将两个链表中的节点顺序对比，小者加入结果尾部
     */
    private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            if (l1 == null && l2 == null) {
                return null;
            } else {
                return l1 == null ? l2 : l1;
            }
        }
        ListNode result = null;
        if (l1.val < l2.val) {
            result = l1;
            result.next = mergeTwoLists(l1.next, l2);
        } else {
            result = l2;
            result.next = mergeTwoLists(l1, l2.next);
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode listNode6 = new ListNode(4, null);
        ListNode listNode5 = new ListNode(3, listNode6);
        ListNode listNode4 = new ListNode(1, listNode5);

        ListNode listNode3 = new ListNode(3, null);
        ListNode listNode2 = new ListNode(2, listNode3);
        ListNode listNode1 = new ListNode(1, listNode2);

        ListNode node = mergeTwoLists(listNode1, listNode4);
        System.out.println("node = " + node);
    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
